package com.aigis.big4.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.StringTokenizer;

public class Average2 {
    public static class AverageMapper extends Mapper<Object, Text, Text,IntWritable>{

        @Override
        protected void map(Object key,Text value,Context context) throws IOException, InterruptedException {
            //行分割数据
            StringTokenizer st=new StringTokenizer(value.toString().trim(),"\n");

            while (st.hasMoreTokens()){
               // 分割每行数据
               StringTokenizer stl=new StringTokenizer(st.nextToken());
               String name=stl.nextToken();
               String score=stl.nextToken();
               context.write(new Text(name),new IntWritable(Integer.parseInt(score)));
            }
        }
    }

    public static class AverageReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
        int count=0;
        int sum=0;
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            for (IntWritable val:values){
               count++;
               sum+=val.get();
            }
            int average = (int)sum/count;
            System.out.println(sum+"--"+count+"--"+average);
            context.write(key,new IntWritable(average));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        args= new String[]{"hdfs://127.0.0.1:9000/test/averageScore/input","hdfs://127.0.0.1:9000/test/averageScore/output"};

        Configuration conf= new Configuration();
        conf.set("mapred.job.tracker", "localhost:9001");
        Job job=new Job(conf,"average");
        job.setJarByClass(Average2.class);
        job.setMapperClass(Average2.AverageMapper.class);
        job.setReducerClass(Average2.AverageReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        System.out.println(job.waitForCompletion(true)? 0:1);
    }
}
